<?php
    header('content-type:text/html;charset="utf-8"');
    //定义统一返回格式
    $responseData = array("code" => 0,"message" => "");
    // var_dump($_POST);
    //取出传过来的数据
    $goodname = $_POST["goodname"];
    $goodprice = $_POST["goodprice"];
    $goodsell = $_POST["goodsell"];
    $stock = $_POST["stock"];
    $img = $_POST["img"];
    $object = $_POST["object"];
    $time = $_POST["time"];


    //验证
    if(!$goodname){
        $responseData["code"] = 1;
        $responseData["message"] = "商品名不能为空";
        echo json_encode($responseData);
        exit;
    }
    if(!$goodprice){
        $responseData["code"] = 2;
        $responseData["message"] = "租价不能为空";
        echo json_encode($responseData);
        exit;
    }
    if(!$goodsell){
        $responseData["code"] = 3;
        $responseData["message"] = "售价不能为空";
        echo json_encode($responseData);
        exit;
    }
    if(!$stock){
        $responseData["code"] = 4;
        $responseData["message"] = "库存不能为空";
        echo json_encode($responseData);
        exit;
    }

    // 1.连接数据库
    $link = mysqli_connect("localhost","root","root");

    // 2.判断是否连接成功
    if(!$link){
        $responseData['code'] = 5;
        $responseData['message'] = "数据库连接失败";
        // 返回到前台页面
        echo json_encode($responseData);
        exit; //结束后续操作
    }

    //3.设置字符集
    mysqli_set_charset($link,"utf8");

    //4.选择数据库
    mysqli_select_db($link,"租售系统");

    //5.准备sql语句将数据插入数据库
    $sql = "INSERT INTO goods(goodname,goodprice,goodsell,stock,img,object,data) VALUES
    ('{$goodname}','{$goodprice}','{$goodsell}','{$stock}','{$img}','{$object}','{$time}')";


    //6.再次发送sql
    $res = mysqli_query($link,$sql);

    //返回布尔值
    if(!$res){
        //添加失败
        $responseData["code"] = 6;
        $responseData["message"] = "添加失败了";
        echo json_encode($responseData);
        exit;
    }else{
        //添加成功
        $responseData["message"] = "添加成功";
        echo json_encode($responseData);
    }

    //8.关闭数据库
    mysqli_close($link);
?>